package com.copm.demonstrationsystem.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.resource.GzipResourceResolver;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.concurrent.TimeUnit;

/**
 * @author chuyunfei
 * @date: 2018/4/1
 * @description: web层的配置类
 */
@Configuration
@EnableSwagger2
public class WebConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/")
                .setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePrivate())
                .resourceChain(true)
                .addResolver(new GzipResourceResolver());
        super.addResourceHandlers(registry);
    }

    /**
     * 1、解决ajax的跨域请求问题
     *      参考资料：https://www.jianshu.com/p/d05303d34222
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry){
        //对整个应用的跨域请求进行处理
        registry.addMapping("/")
                //允许的主机源：请求域，允许全部请求域
                .allowedOrigins("*")
                //允许的请求方法
                .allowedMethods("GET","POST","DELETE","PUT")
                //允许cookie跨域
                .allowCredentials(true)
                //允许的头信息
                .allowedHeaders("*");
        super.addCorsMappings(registry);
    }

    /**
     * 1、用于生成API的swagger对象
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.copm.demonstrationsystem.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("演示系统API列表")
                .description("如果有相关问题请联系：")
                .contact("袁佰煜、楚云飞")
                .version("1.0")
                .build();
    }
}
